package com.sfx.concurrent.demo.concurrent.Lock.AQS1;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-04-15
 * Time: 14:37
 */
//自定义锁
public class MyLock implements Lock {//实现lock接口

    //独占锁 同步器 -->局域AQS同步器 (抽象队列同步器)
    class MySync extends AbstractQueuedSynchronizer{
        @Override //尝试获取锁
        protected boolean tryAcquire(int arg) {
            if(compareAndSetState(0,1)) {
                //修改当前持有锁线程owner 为 当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                setState(1);//成功加上锁
                return true;
            }
            return false;
        }

        @Override //尝试释放锁
        protected boolean tryRelease(int arg) {
            setExclusiveOwnerThread(null);//修改当前持有锁线程owner 为 null
            //释放锁
            setState(0);
            return true;
        }

        @Override //当前线程是否持有锁
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
        public Condition newCondition() {
            return new ConditionObject();
        }
    }

    private MySync sync = new MySync();

    @Override //加锁, 加锁失败则进入阻塞队列
    public void lock() {
        sync.acquire(1);
    }

    @Override //加锁可以被打断
    public void lockInterruptibly() throws InterruptedException {
        sync.acquireInterruptibly(1);
    }

    @Override //尝试加锁,
    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return sync.tryAcquireNanos(1,unit.toNanos(time));
    }

    @Override //释放锁并且唤醒被阻塞的线程
    public void unlock() {
        sync.release(1);
    }

    @Override //返回一个条件变量
    public Condition newCondition() {
        return sync.newCondition();
    }
}